using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[DisallowMultipleComponent]
public sealed class UIReuseItem : UIBehaviour, IPointerClickHandler
{
    [SerializeField] bool _selectable;
    List<UIReuseList> _nestReuseLists;
    UIVariableHelper _variableHelper;

    public RectTransform RectTransform { get; private set; }
    public Action OnSelect { get; set; }

    protected override void Awake()
    {
        base.Awake();

        RectTransform = GetComponent<RectTransform>();
        if (_selectable) gameObject.AddComponent<EmptyRaycast>();
        
        _variableHelper = GetComponent<UIVariableHelper>();
        if (_variableHelper == null)
        {
            _variableHelper = gameObject.AddComponent<UIVariableHelper>();
        }
    }

    public List<UIReuseList> GetNestReuseList()
    {
        if (_nestReuseLists == null)
        {
            _nestReuseLists = new List<UIReuseList>();
            var variables = _variableHelper?.GetVariables();
            if (variables != null)
            {
                foreach (var obj in variables)
                {
                    if (obj != null && obj.TryGetComponent<UIReuseList>(out var reuseList))
                        _nestReuseLists.Add(reuseList);
                }
            }
        }
        return _nestReuseLists;
    }

    public UIVariableHelper GetVariableHelper()
    {
        // 在编辑器模式下，_variableHelper 可能为 null（因为 Awake 不会执行）
        // 所以需要实时获取
        if (_variableHelper == null)
        {
            _variableHelper = GetComponent<UIVariableHelper>();
        }
        return _variableHelper;
    }


    void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
    {
        var handlers = GetComponentsInChildren<IPointerClickHandler>();
        foreach (var handler in handlers)
        {
            if (handler == this as IPointerClickHandler) continue;

            if (handler is UIBehaviour behaviour)
            {
                if (!behaviour.enabled || !behaviour.gameObject.activeInHierarchy)
                    continue;

                var rectTransform = behaviour.GetComponent<RectTransform>();
                if (RectTransformUtility.RectangleContainsScreenPoint(rectTransform, eventData.position, eventData.enterEventCamera))
                {
                    if (behaviour is UIReuseItem reuseItem)
                    {
                        if (!reuseItem._selectable) continue;

                        ExecuteEvents.Execute(reuseItem.gameObject, eventData, ExecuteEvents.pointerClickHandler);
                        return;
                    }
                    else
                    {
                        handler.OnPointerClick(eventData);
                        return;
                    }
                }
            }
        }
        if (!_selectable) return;

        OnSelect?.Invoke();
    }


    public void Layout(bool immediately = false)
    {
        if (immediately)
            LayoutRebuilder.ForceRebuildLayoutImmediate(RectTransform);
        else
            LayoutRebuilder.MarkLayoutForRebuild(RectTransform);
    }
}

